package com.example.yuntiku.Servlet;

import com.example.yuntiku.Email.SendEmail;
import com.example.yuntiku.dao.impl.UsersDao;
import com.example.yuntiku.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

@WebServlet(name = "logonServlet", value = "/logonServlet")
public class logonServlet extends HttpServlet {
    private static String message;
    private static String emails;

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        try {
            String email = request.getParameter("email"); // 获取邮箱

            SendEmail sendEmail = new SendEmail();           //定义发送邮件工具类
            message = sendEmail.generateCaptcha();           //调用工具类的生成验证码方法
            emails = email;                                  //获取用户本身的邮件
            sendEmail.send(email,message);                   //发送邮件
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        // 处理乱码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        // 获得请求参数
        String email = request.getParameter("email");
        String uname = request.getParameter("uname");
        String upwd = request.getParameter("upwd");
        String Code = request.getParameter("Code");
        PrintWriter printWriter = response.getWriter();

        // 调用dao进行查询
        UsersDao usersDao = new UsersDao();
        if (usersDao.isEmailRegistered(email)) {
            // 邮箱已被注册，弹出提示
            printWriter.println("该邮箱已被注册");
        } else if (Objects.equals(message, Code)) {
            // 定义要添加的实体类对象
            User users = new User();
            users.setEmail(email);
            users.setUname(uname);
            users.setUpwd(upwd);

            // 调用dao进行添加
            usersDao.insert(users);
            printWriter.println("ok了兄弟们");
        } else {
            printWriter.println("验证码错误");
        }
    }
}